import { Component, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { Events } from '@core/services/events/Events';
import { FormService } from '@core/services/form.service';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import { deepClone } from '../../../utils/utils';
import { Subject, Subscription } from 'rxjs/index';
import { ApesModalService } from '@shared/apes/modal';
import { ApesPreviewDialogComponent } from '@shared/ag-grid-ext/upload-component/apes-previewDialog.component';
import { HtmlToCanvasService } from '@core/services/tool/htmlToCanvas.service';

@Component({
  selector: 'apes-shopping-car',
  templateUrl: './shoppingCar.component.html',
  styleUrls: ['./shoppingCar.component.scss'],
})

export class ShoppingCarComponent implements OnInit, OnDestroy {

  baseData: any;
  selectAll: boolean = true;
  isLoading$ = new Subject(); // 加载中
  // loadingStep = 0; // 加载中步骤
  finishSum: any = 0;   // 结束数
  sum: any = 0;         //总数
  percent: any = 0;     // 百分比
  isLoadingSubscription: Subscription;
  isLoading: boolean = false;
  stopPost: boolean = false;
  resData: any[] = [];
  custom: any = 'servicePlan';           // 使用插件页面 servicePlan，lossQuotation
  shoppingData: any[] = [
    // {
    //   QCCPMC: 'CGH0718C00340',
    //   vin: 'LHGGJ7645J2039161',
    //   parts: [
    //     {
    //       selected: false,
    //       expand: false,
    //       id: 12,
    //       partCode: 123450,
    //       partName: '玻璃',
    //       typeName: '玻璃',
    //       orderQuantity: 4,
    //       url: 'fileserver/view/5eafb54488ecd61924a9dd10',
    //       // products: [{
    //       //   name: '玻璃',
    //       //   price: 995,
    //       //   unit: '块',
    //       //   remark: '原包',
    //       //   local: 0,
    //       //   central: 2,
    //       //   orderQuantity: 1,
    //       // },
    //       //   {
    //       //     name: '玻璃',
    //       //     price: 995,
    //       //     unit: '块',
    //       //     remark: '原包',
    //       //     local: 0,
    //       //     central: 2,
    //       //     num: 1,
    //       //   },
    //       // ],
    //     },
    //     {
    //       selected: false,
    //       expand: false,
    //       id: 13,
    //       partCode: 123450,
    //       partName: '玻璃',
    //       typeName: '玻璃',
    //       orderQuantity: 4,
    //       url: 'fileserver/view/5eafb54488ecd61924a9dd10',
    //       // products: [{
    //       //   name: '玻璃',
    //       //   price: 995,
    //       //   unit: '块',
    //       //   remark: '原包',
    //       //   local: 0,
    //       //   central: 2,
    //       //   num: 1,
    //       // },
    //       //   {
    //       //     name: '玻璃',
    //       //     price: 995,
    //       //     unit: '块',
    //       //     remark: '原包',
    //       //     local: 0,
    //       //     central: 2,
    //       //     num: 1,
    //       //   },
    //       // ],
    //     },
    //   ],
    // },
  ];
  postTime: any;

  constructor(
    private apiService: ApiService,
    private msg: ApesMessageService,
    protected events: Events,
    protected formService: FormService,
    private contextService: ApesContextMenuService,
    private modalService: ApesModalService,
    private h2c: HtmlToCanvasService,
  ) {

  }

  ngOnInit(): void {
    this.events.subscribe('assemblyDrawing/assemblyDrawing', data => {
      this.getShopCarData(data);
    });
    if (this.formService.formData.hasOwnProperty('key')) {
      this.getShopCarData(this.formService.formData['key']);
    }

    this.isLoadingSubscription = this.isLoading$.subscribe((data: number) => {
      if (!this.stopPost) {
        this.finishSum += data;
        // console.log('step' + this.loadingStep);
        this.percent = parseInt((this.finishSum / this.sum) * 100 + '');
        if (this.finishSum == this.sum) {
          this.isLoading = false;
          this.resData.forEach((res) => {
            if (this.custom == 'servicePlan') {
              this.baseData.model['servicePlanItems'].push(res);
            } else if (this.custom == 'lossQuotation') {
              this.baseData.model['lossQuotationItems'].push(res);
            } else if (this.custom == 'servicePlan2') {
              this.baseData.model['fittingsItems'].push(res);
            }
          });
          let params = {
            'OAInterface': false,
            'formId': this.baseData.currentUrl,
            'routerTask': true,
            'api': 'cad-shopCar',
            'body': this.baseData.model,
          };
          this.formService.navigateToForm(params);
        } else {
          this.isLoading = true;
        }
      } else {
        this.isLoading = false;
        this.resData = [];
      }
    });
  }

  ngOnDestroy(): void {
    this.isLoadingSubscription.unsubscribe();
  }

  black() {
    if (!this.baseData) return;
    let resultData = {
      // model: this.baseData.model,
      // cacheData: this.baseData.cacheData,
      // menuData: this.baseData.menuData,
      // modelInfo: this.baseData.modelInfo,
      // currentUrl: this.baseData.currentUrl,
      baseData: this.baseData,
      shoppingData: this.shoppingData,
    };
    let api = 'assemblyDrawing/assemblyDrawing';
    let config = { OAInterface: false };
    this.contextService.openContextLink(resultData, api, config);
  }

  getShopCarData(data) {
    delete this.formService.formData['key'];
    // console.log('获取到的购物车数据', data);
    this.baseData = deepClone(data);
    this.custom = this.baseData.custom;
    this.shoppingData = data.shoppingData;
    this.checkSelectAll();
  }

  // 检查数量
  checkNum(params) {
    let num = params.orderQuantity;
    params.orderQuantity = parseInt(num);
  }

  // 修改数量
  setNum(params, type) {
    let num;
    if (type == 'add') {
      num = params.orderQuantity + 1;
    } else if (type == 'prune') {
      num = params.orderQuantity - 1;
    }
    if (num <= 0) {
      num = 1;
    }
    params.orderQuantity = parseInt(num);
  }

  // 点击全选
  clickSelectAll() {
    this.shoppingData[0]['parts'].forEach((row) => {
      row['selected'] = this.selectAll;
    });
  }

  // 检查全选
  checkSelectAll() {
    let selectAll = true;
    this.shoppingData[0]['parts'].forEach((row) => {
      if (row['selected'] == false) {
        return selectAll = false;
      }
    });
    this.selectAll = selectAll;
  }

  checkSelectParts() {
    let select = false;
    this.shoppingData[0]['parts'].forEach((row) => {
      if (row['selected'] == true) {
        select = true;
      }
    });
    return select;
  }

  // 已选商品数
  partsNumber() {
    let num = 0;
    if (this.shoppingData.length > 0) {
      this.shoppingData[0]['parts'].forEach((row) => {
        if (row['selected'] == true) {
          num += 1;
        }
      });
    }
    return num;
  }

  // 删除
  deleteShop(data, i) {
    // this.shoppingData.splice(i, 1);
    // let data = this.shoppingData[0]['parts'];
    // data.splice(i, 1);
    // this.shoppingData[0]['parts'] = data
    this.shoppingData[0]['parts'] = this.shoppingData[0]['parts'].filter(d => d != data);
  }

  // 清空
  removeAll() {
    if (this.isLoading) return;
    this.modalService.confirm({
      apesTitle: '是否清空全部配件篮配件?',
      apesOkText: '确认',
      apesOnOk: () => {
        this.shoppingData[0]['parts'] = [];
      },
      apesCancelText: '取消',
      // apesOnCancel: () => {}
    });
  }

  showPartsName(value) {
    let name = '';
    if (value && value.length != 0) {
      if (value.length == 1) {
        name = value[0]['PJMC'];
      } else {
        value.forEach((res) => {
          name += (res['PJMC'] + '; ');
        });
      }
    }
    return name;
  }

  filterName(value) {
    let name = '';
    if (value) {
      name = value.replace(/\$\$/g, '\r\n');
    }
    return name;
  }

  goProgram() {
    if (!this.baseData) return;
    // console.log('选中数据', this.shoppingData);
    // console.log('主表数据', this.baseData);
    let shoppingData = deepClone(this.shoppingData[0]['parts']);
    let submit = [];
    shoppingData.forEach((res) => {
      if (res['selected']) {
        submit.push(res);
      }
    });

    if (submit.length == 0) {
      this.msg.error('请选择需要订购的配件。');
      return;
    }

    // let data = {
    //   ...this.baseData['model'],
    //   fitting: submit,
    // };


    // console.log('SKU调用', data);
    this.isLoading = true;
    // this.postTime = setTimeout(()=>{
    //   this.msg.error('请求服务超时，请重新导入到服务方案！');
    //   clearTimeout(this.postTime);
    //   this.isLoading = false;
    // },60000);
    this.sum = submit.length;
    this.stopPost = false;
    this.finishSum = 0;
    this.percent = 0;
    this.resData = [];
    submit.forEach((sub) => {
      if (sub['parts'].length == 0) {
        let todoData = deepClone(sub);
        this.compileTodo(todoData);
      }
      if (sub.hasOwnProperty('highLowconfig')) {
        sub.oldPartCode = sub.partCode;
        sub.partCode = this.baseData['modelInfo']['CXPJID'];
      }
      let data = {
        ...this.baseData['model'],
        fitting: [sub],
        custom: this.custom == 'lossQuotation' ? 'lossQuotation' : null,
      };
      this.postSKU(data);
    });

  }

  postSKU(data) {
    let api = 'cm.product.queryProduct';
    let partName = data.fitting[0].partName;
    this.apiService.post(api, data).subscribe((body) => {
      // console.log('返回结果', body);
      if (body && body.length > 0) {

        body.forEach((res) => {
          this.shoppingData[0]['parts'].forEach((shop) => {
            if (shop.partCode == res.partCode || shop.partCode == res.oldPartCode) {
              // let name = this.interceptionName(shop.url);
              res['partName'] = shop['partName'].replace(/[ ]/g, '');
              res['imageSN'] = shop['imageSN'];
              res['saleQty'] = shop['orderQuantity'];
              // res['mapAddress'] = [{
              //   'fileName': name,
              //   'size': 0,
              //   'name': name,
              //   'id': '',
              //   'type': 'image/jpeg',
              //   'url': shop.url,
              // }];
              res['mapAddress'] = shop['urls'];
              if (shop['positionConfirma'] && !shop.hasOwnProperty('priceForward')) {
                res['remarks'] = shop['positionConfirma'];
              }
              if (!res.isMatchParts) {
                res.partCode = '';
              }
              res['fourSPrice'] = shop['price'];
            }
          });
          if (res['mapAddress'].length != 0) {
            this.imgToFile(res);
          } else {
            this.resData.push(res);
            this.isLoading$.next(1);
          }
        });

      } else {
        let errorText = partName + '生成对应商品有误，请重新导入';
        this.msg.error(errorText, { 'apesDuration': 3000 });
        this.stopPost = true;
        this.sum = 0;
        this.finishSum = 0;
        this.percent = 0;
        this.isLoading = false;
        this.resData = [];
      }
    });
  }


  imgToFile(param) {
    console.log('图片转换', param);
    let loading = 0;
    let tagMapAddress = [];
    param['mapAddress'].forEach((res) => {
      loading += 1;
      this.h2c.htmlToCanvas(res, (file) => {
        console.log(file);
        loading -= 1;
        tagMapAddress = [...tagMapAddress, ...file];
        if (loading == 0) {
          param['tagMapAddress'] = tagMapAddress;
          this.resData.push(param);
          this.isLoading$.next(1);
        }
      });
    });


  }

  // 推送待编译待办
  compileTodo(parts) {
    let api = 'autoparts.epcPartCodeParse.create';
    let data = {
      vin: this.baseData['cacheData']['vin'],
      pzcxid: this.baseData['cacheData']['PZCXID'],
      qccpmc: this.baseData['cacheData']['QCCPMC'],
      epcVersion: this.baseData['cacheData']['epcVersion'] ? this.baseData['cacheData']['epcVersion'] : '暂缺',
      menuName: parts['subGroupName'] ? parts['subGroupName'] : this.baseData['subMenuData']['name'],
      partCode: parts['partCode'],
      partName: parts['partName'],
      imageSN: parts['imageSN'],
      imageUrl: parts['urls'],
      dept: this.baseData['model']['saleDept'],
      categories: [],
      errorFlag: false,
    };
    // console.log('推送待编译零件', data);
    this.apiService.post(api, data).subscribe((body) => {
      // console.log(body);
    });
  }

  interceptionName(name) {
    let arr = name.split('/');
    let res = arr[arr.length - 1];
    return res;
  }

  showImg(data) {
    let option = {
      title: '预览图片',
      _fileList: data,
    };

    this.openUploadDialog(option, (result: any) => {
      // console.log(result);
    });
  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };

    const openDialog = dialog ? dialog : ApesPreviewDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
            // dialogRef.close();
          },
        },
        {
          label: '确定',
          type: 'primary',
          onClick: (componentInstance) => {
            // console.log(componentInstance);
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

}
